package zhai.docking.alipay.service.biz;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import zhai.docking.alipay.constant.LogConstant;
import zhai.docking.alipay.constant.StringConstant;
import zhai.docking.alipay.domain.base.alipay.BaseAlipayImageUploadIn;
import zhai.docking.alipay.domain.base.alipay.BaseAlipayImageUploadOut;
import zhai.docking.alipay.domain.base.common.Result;
import zhai.docking.alipay.domain.biz.alipay.AlipayImageUploadOut;
import zhai.docking.alipay.service.base.alipay.api.BaseAlipayApiImageSer;
import zhai.docking.alipay.util.FileUtil;
import zhai.docking.alipay.util.SnowflakeUtil;
import zhai.docking.alipay.util.StringUtil;

import java.io.File;

/**
 * @author Created by 翟凤玺
 * @package zhai.docking.alipay.service.biz
 * @project-name zhai-docking-alipay
 * @description 支付宝-图片-服务实现
 * @create-datetime 2021/1/22 14:42
 */
@Slf4j
@Service
public class AlipayImgSerImpl implements AlipayImgSer {

    private static final String BUSINESS_NAME = "【支付宝-图片 服务】";
    private static final String METHOD_UPLOAD = "（上传）";

    @Autowired
    BaseAlipayApiImageSer baseAlipayApiImageSer;
    @Autowired
    SnowflakeUtil snowflakeUtil;

    @SneakyThrows
    @Override
    public Result upload(MultipartFile in) {
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_UPLOAD, LogConstant.IN, in.getName()));
        /** 操作：重命名文件名 */
        String imageName = StringUtil.join(snowflakeUtil.nextId(), StringConstant.POINT, FileUtil.getFileType(FileUtil.getFileName(in)));
        File file = new File(imageName);
        FileUtil.copyInputStreamToFile(in.getInputStream(), file);
        BaseAlipayImageUploadOut upload = null;
        try {
            /** 操作：上送-支付宝图片接口 */
            BaseAlipayImageUploadIn uploadIn = new BaseAlipayImageUploadIn();
            uploadIn.setImageFile(file);
            upload = baseAlipayApiImageSer.upload(uploadIn);
        } finally {
            if (file.exists()) {
                file.delete(); // 删除临时文件
            }
        }
        /** 结果：转换 */
        if (!upload.isSuccess()) {
            log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_UPLOAD, LogConstant.RESULT, LogConstant.FAIL, upload.getCode(), upload.getMsg()));
            return Result.failure(upload.getCode(), upload.getMsg());
        }
        AlipayImageUploadOut result = new AlipayImageUploadOut();
        result.setImgCode(upload.getImageId());
        log.info(StringUtil.join(BUSINESS_NAME, LogConstant.SERVICE, METHOD_UPLOAD, LogConstant.RESULT, LogConstant.SUCCESS));
        return Result.success(result);
    }
}